package com.itouch.bracelet.activity;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONObject;

import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.itouch.bracelet.R;
import com.itouch.bracelet.adapter.MedicationAdapter;
import com.itouch.bracelet.adapter.MedicationAdapter.DeleteCallback;
import com.itouch.bracelet.bean.BaseResult;
import com.itouch.bracelet.bean.LoginUser;
import com.itouch.bracelet.bean.Medication;
import com.itouch.bracelet.bean.MedicationResult;
import com.itouch.bracelet.cache.UserCache;
import com.itouch.bracelet.diseaseinfo.Constants;
import com.itouch.widget.ActionSheet;
import com.itouch.widget.ActionSheet.ActionSheetListener;
import com.itouch.widget.XListView;
import com.itouch.widget.XListView.IXListViewListener;

public class MedicationListActivity extends BaseActivity implements
		IXListViewListener, DeleteCallback, ActionSheetListener {

	private XListView listview;
	private ArrayList<Medication> list;
	private MedicationAdapter adapter;
	private int page_index = 1;
	private static final int page_size = 10;
	private int type;
	private int clickPosition = -1;
	private boolean isMother = false;

	@Override
	protected int setContentViewById() {
		return R.layout.activity_medication_list;
	}

	public void add_medication(View view) {
		Intent it = new Intent(context, AddMedicationActivity.class);
		it.putExtra("type", type);
		startActivity(it);
	}

	@Override
	protected void initViews() {

		type = getIntent().getIntExtra("type", -1);

		listview = (XListView) findViewById(R.id.listview);
		listview.setPullRefreshEnable(true);
		listview.setPullLoadEnable(false);
		listview.setXListViewListener(this);
		listview.setRefreshTime(getTime());
		// listview.setOnItemClickListener(this);
		list = new ArrayList<Medication>();

		isMother = 0==type ? true : false;

		adapter = new MedicationAdapter(context, list, isMother);
		adapter.setDeleteCallback(this);
		listview.setAdapter(adapter);
		getList();
	}

	private void getList() {
		Uri.Builder builder = Uri.parse(Constants.GET_MEDICATION).buildUpon();
		// /customerId=86&filter_S_parentId=0&page=1&rows=10
		LoginUser user = UserCache.getOauth(context);

		if (isMother) {
			builder.appendQueryParameter("customerId", user.getUserId());
		} else {
			builder.appendQueryParameter("customerId", user.getChildlist().get(user.childPosition).getId());
		}

		builder.appendQueryParameter("filter_S_parentId", type + "");
		builder.appendQueryParameter("page", page_index + "");
		builder.appendQueryParameter("rows", page_size + "");

		if (page_index == 1) {
			list.clear();
		}
		Log.d("GET_MEDICATION", "GET_MEDICATION" + builder.toString());

		show();
		getJSONByVolleyGET(builder.toString(),
				new Response.Listener<JSONObject>() {

					@Override
					public void onResponse(JSONObject arg0) {
						disMiss();
						onLoad();
						Log.d("GET_MEDICATION",
								"GET_MEDICATION" + arg0.toString());
						try {
							MedicationResult a = new Gson().fromJson(
									arg0.toString(), MedicationResult.class);
							if (a == null) {
								return;
							}
							if (a.isFlag()) {
								List<Medication> xx = a.getRows();
								if (xx != null&&xx.size()>0) {
									list.addAll(xx);
									adapter.notifyDataSetChanged();
									if (xx.size() < page_size) {
										setPullLoadEnable(false);
									} else {
										setPullLoadEnable(true);
									}
								}

							} else {
								Toast.makeText(context, a.getMsg() + "",
										Toast.LENGTH_LONG).show();
							}
						} catch (Exception e) {
						}
					}

				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError arg0) {
						disMiss();
						onLoad();
						Toast.makeText(context,
								getString(R.string.net_error) + "",
								Toast.LENGTH_LONG).show();
					}
				});

	}

	// http://127.0.0.1:8083/mobi/medication/deleteMedication?id=20
	private void deleteRow(String id) {
		Uri.Builder builder = Uri.parse(Constants.DELETE_MEDICATION)
				.buildUpon();
		// /customerId=86&filter_S_parentId=0&page=1&rows=10
		builder.appendQueryParameter("id", id);
		clickPosition = -1;
		Log.d("DELETE_MEDICATION", "DELETE_MEDICATION" + builder.toString());

		show();
		getJSONByVolleyGET(builder.toString(),
				new Response.Listener<JSONObject>() {

					@Override
					public void onResponse(JSONObject arg0) {
						disMiss();
						Log.d("DELETE_MEDICATION",
								"DELETE_MEDICATION" + arg0.toString());
						try {
							BaseResult a = new Gson().fromJson(arg0.toString(),
									BaseResult.class);
							if (a == null) {
								return;
							}
							if (a.isFlag()) {
								page_index = 1;
								getList();

							} else {
								Toast.makeText(context, a.getMsg() + "",
										Toast.LENGTH_LONG).show();
							}
						} catch (Exception e) {
						}
					}

				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError arg0) {
						disMiss();
						Toast.makeText(context,
								getString(R.string.net_error) + "",
								Toast.LENGTH_LONG).show();
					}
				});

	}

	@Override
	public void onRefresh() {
		page_index = 1;
		getList();
	}

	@Override
	public void onLoadMore() {
		page_index++;
		getList();
	}

	private void onLoad() {
		if (null != listview) {
			listview.stopRefresh();
			listview.stopLoadMore();
			listview.setRefreshTime(getTime());
		}
	}

	private void setPullLoadEnable(boolean temp) {
		if (listview != null) {
			listview.setPullLoadEnable(temp);
		}
	}

	@Override
	protected void initData() {

	}

	@Override
	public void delete(int position) {
		clickPosition = position;

		setTheme(R.style.ActionSheetStyleIOS7);
		ActionSheet.createBuilder(this, getSupportFragmentManager())
				.setCancelButtonTitle("取消").setOtherButtonTitles("确定")
				.setCancelableOnTouchOutside(true).setListener(this).show();

	}

	@Override
	public void onDismiss(ActionSheet actionSheet, boolean isCancel) {
	}

	@Override
	public void onOtherButtonClick(ActionSheet actionSheet, int index) {
		if (clickPosition < 0) {
			return;
		}
		try {
			Medication temp = list.get(clickPosition);
			deleteRow(temp.getId());

		} catch (Exception e) {

		}

	}

}
